#include "mycanvas.h"
#include "myinterpreter.h"
#include "mytracefactory.h"

MyCanvas::MyCanvas(Scene *_scene){
    this->scene = _scene;
    
    this->interpreter = new MyInterpreter();
    this->interpreter->setTraceFactory(new MyTraceFactory());
    this->interpreter->setScene(this->scene);
}

void MyCanvas::onPressCursor(Cursor &cursor){
    Point scene_point = scene->getScenePoint(cursor);
    cursor.setScenePoint(scene_point);
    this->interpreter->addCursor(cursor);
}


void MyCanvas::onMoveCursor(Cursor &cursor){
    Point scene_point = scene->getScenePoint(cursor);
    cursor.setScenePoint(scene_point);
    this->interpreter->addCursor(cursor);
}

void MyCanvas::onReleaseCursor(Cursor &cursor){
    Point scene_point = scene->getScenePoint(cursor);
    cursor.setScenePoint(scene_point);
    this->interpreter->addCursor(cursor);    
    this->interpreter->finishTrace(cursor.getId());    
}

void MyCanvas::paint(){
    glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);

    glColor3f(1.0f, 0.0f, 0.0f);
    glLineWidth(5);
    map<int,Trace> &traces = this->interpreter->getSketch().getTraces();
    for (map<int,Trace>::iterator it = traces.begin(); it != traces.end(); it++){
        glBegin(GL_LINE_STRIP);
        vector<Cursor> &cs = it->second.getCursors();
        for (unsigned int i=0; i < cs.size(); i++){
            glVertex2f( cs[i].getScenePoint().getX(), cs[i].getScenePoint().getY() );
        }
        glEnd();
    }
    
    this->scene->drawPolygons();
    this->scene->drawLines();
    glFlush();
}

void MyCanvas::initialize(){
    glClearColor(1.0, 1.0, 1.0, 1.0);
}

void MyCanvas::resizeCanvas(int _width, int _height){
    Viewport &viewport = this->scene->getViewport();
    Window &window = this->scene->getWindow();

    if (_width  == 0) _width  = 1;
    if (_height == 0) _height = 1;
    viewport.width = _width;
    viewport.height = _height;
    
    glViewport(viewport.left, viewport.top, viewport.width, viewport.height);
    glMatrixMode(GL_PROJECTION);
    glLoadIdentity();
    
    glOrtho(window.left, window.right, window.bottom, window.top, -10.0, 0.0);
    
    glMatrixMode(GL_MODELVIEW);
    glLoadIdentity();
}
